package cn.gzsxt.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.annotation.SessionScope;

import cn.gzsxt.annotation.AdminSessionUpdate;
import cn.gzsxt.annotation.TokenForm;
import cn.gzsxt.service.ModularService;
import cn.gzsxt.service.RoleService;
import cn.gzsxt.utils.Global;
import cn.gzsxt.utils.Page;

@Controller
@SessionScope
@RequestMapping(value="/role")
public class RoleController {
	
private static final Logger LOGGER=LogManager.getLogger(RoleController.class);
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private ModularService modularService;
	
	/**
	 * 实现角色增加
	 * @param entity
	 * @return
	 */
	@RequestMapping(value="/addRole")
	@TokenForm(remove=true)
	@AdminSessionUpdate
	public String  addRole(@RequestParam Map<String, Object> entity,String[] perminssionIds,HttpServletRequest request){
		LOGGER.debug("增加角色"+entity+"，权限编号集："+Arrays.toString(perminssionIds));
		
		//需要将perminssionIds数组转换成1,2,3,4,5.... 字符串
		StringBuilder builder=new StringBuilder(Arrays.toString(perminssionIds));
		//删除 [] 中括号
		builder.delete(0, 1);
		builder.delete(builder.length()-1, builder.length());
		
		entity.put("ROLE_PERMISSIONS", builder.toString());
	
		//将角色的数据插入到数据库
		try {
			Map<String, Object> role = roleService.addRole(entity);
			if (role!=null) {
				request.setAttribute("role_add_msg", "增加角色成功");
			}else{
				request.setAttribute("role_add_msg", "增加角色失败");
			}
		} catch (Exception e) {
			request.setAttribute("role_add_msg", "出现未知异常，请联系管理员");
			e.printStackTrace();
		}
		
		return "forward:/role/toRoleAdd";
	}
	
	/**
	 * 删除角色记录
	 * @param roleId
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/deleteRoleById/{roleId}")
	@AdminSessionUpdate
	public String deleteRoleById(@PathVariable Long roleId,HttpServletRequest request){
		
		//通过Id删除记录
		roleService.deleteRoleByIds(roleId);
		
		//通过路径跳转回列表
		return "forward:/role/toRoleList/0";
	}
	
	/**
	 * 批量删除多条数据
	 * @return
	 */
	@RequestMapping(value="/deleteRoleByIds")
	@AdminSessionUpdate
	public String deleteRoleByIds(String[] roleId){
		LOGGER.debug("批量删除角色"+Arrays.toString(roleId));
		
		//通过角色编好数组删除记录
		roleService.deleteRoleByIds((Object[])roleId);
		
		//通过路径跳转回列表
		return "forward:/role/toRoleList/0";
	}
	
	/**
	 * 更新角色记录
	 * @param entity
	 * @return
	 */
	@RequestMapping(value="/editRole")
	@AdminSessionUpdate
	public String editRole(@RequestParam Map<String, Object> entity,String[] perminssionIds,HttpServletRequest request){
		LOGGER.debug("更新角色："+entity);
		
		//需要将perminssionIds数组转换成1,2,3,4,5.... 字符串
		StringBuilder builder=new StringBuilder(Arrays.toString(perminssionIds));
		//删除 [] 中括号
		builder.delete(0, 1);
		builder.delete(builder.length()-1, builder.length());
		
		entity.put("ROLE_PERMISSIONS", builder.toString());
	
		try {
			Map<String, Object> role = roleService.editRole(entity);
			if (role!=null) {
				request.setAttribute("role_edit_msg", "更新角色成功");
				request.setAttribute("role", role);
			}else{
				request.setAttribute("role_edit_msg", "更新角色失败");
			}
		} catch (Exception e) {
			request.setAttribute("role_edit_msg", "出现未知异常，请联系管理员");
			e.printStackTrace();
		}
		return "forward:/role/toRoleEdit/"+entity.get("ROLE_ID");
	}
	
	/**
	 * 跳转到角色增加页面
	 * @return
	 */
	@RequestMapping(value="/toRoleAdd")
	
	@TokenForm(create=true)
	public String toRoleAdd(HttpServletRequest request){
		LOGGER.debug("跳转到角色增加页面");
		//封装页面的数据-包括权限的模块
		List<Map<String, Object>> modulars = modularService.findAllModularIncPermission();
		request.setAttribute("modulars", modulars);
		
		return "manager/roleAdd";
	}
	
	/**
	 * 跳转到角色编辑页面，编辑数据必须要标识唯一的记录
	 * 所以必须要传递一个角色编号过来
	 * @return
	 */
	@RequestMapping(value="/toRoleEdit/{roleId}")
	public String toRoleEdit(@PathVariable Long roleId,HttpServletRequest request){
		LOGGER.debug("跳转到编辑角色页面"+roleId);
		//跳转到编辑页面之前，需要将要编辑的角色数据查询出来
		Map<String, Object> role = roleService.findRoleById(roleId);
		request.setAttribute("role", role);
		
		//封装页面的数据-包括权限的模块
		List<Map<String, Object>> modulars = modularService.findAllModularIncPermission();
		request.setAttribute("modulars", modulars);
		
		return "manager/roleEdit";
	}
	
	/**
	 * 跳转到角色列表页面
	 * @param index 数据库索引=页面索引-1。
	 * @param condition 查询的条件
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/toRoleList/{index}")
	public String toRoleList(@PathVariable Integer index,@RequestParam Map<String, Object> condition, HttpServletRequest request) {
		LOGGER.debug("跳转到角色列表");
		if (index==null) {
			index=0;
		}
		//第一步：实现全部角色数据查询
		Page page = roleService.findRoleByConditionToPage(condition, index, Global.RECORD_SIZE);
		//第二步：将数据通过作用域返回到页面
		request.setAttribute("rolePage", page);
		
		return "manager/roleList";
	}


}
